<template>
  <base-content>
    <template>
      <!-- 查询 -->
      <sf-base-search ref="baseSearchEle" :base-searchs="baseSearchs" :base-handles="baseHandles" :base-data="baseFormData" />
      <!-- 列表 -->
      <sf-grid ref="grid" :columns="columns" :operations="operations" :store-config="configs" />
      <!-- 新建/编辑 -->
      <el-dialog title="新建/编辑业务部门" :visible.sync="isShow" :before-close="handleCancleCreate" width="40%">
        <!-- <sf-base-form ref="createAccountForm" width="400px" :eles="eles" /> -->
        <el-form ref="form" :model="form" label-width="180px">
          <el-form-item label="部门类型">
            <el-select v-model="form.dept_type" :disabled="id !== ''" placeholder="请选择部门类型" @change="depChange">
              <el-option label="大区" value="6" />
              <el-option label="运营中心" value="2" />
              <el-option label="咨询中心" value="3" />
              <el-option label="机构" value="4" />
              <el-option label="门店" value="5" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.dept_type == 3 || form.dept_type == 5 || form.dept_type == 2" label="上级部门">
            <el-select v-model="form.dept_parent_id" placeholder="请选择上级部门">
              <el-option v-for="item in depts" :key="item.id" :label="item.dept_name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门名称">
            <el-col :span="16">
              <el-input v-model="form.dept_name" />
            </el-col>
          </el-form-item>
          <el-form-item label="选择地域">
            <el-cascader v-model="selectedOptions" size="large" :options="options" />
          </el-form-item>
          <el-form-item label="详细地址">
            <el-col :span="16">
              <el-input v-model="form.location" />
            </el-col>
          </el-form-item>
          <el-form-item label="邀请码">
            <span>{{ promotion_code || '自动生成' }}</span>
          </el-form-item>
          <el-form-item label="电话号码">
            <el-col :span="10">
              <el-input v-model="form.tel" />
            </el-col>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleCancleCreate">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="handleCreatAccount">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </base-content>
</template>

<script>
import { mapGetters } from 'vuex'
import { queryParams, hasPermission } from '@/utils'
import { createDept, getDeptList, updateDept } from '@/api/authority'
import { provinceAndCityData, CodeToText, TextToCode } from 'element-china-area-data'

export default {
  computed: {
    ...mapGetters(['sidebar']),
    routes() {
      return this.$router.options.routes
    }
  },
  data() {
    return {
      // here is dialog
      isShow: false,
      reSetShow: false,
      options: provinceAndCityData,
      selectedOptions: [],
      loading: false,
      form: {
        tel: '',
        dept_type: '',
        location: '',
        dept_parent_id: '',
        promotion_code: '',
        dept_name: '',
        dept_parent_name: ''
      },
      depts: [],
      promotion_code: '',
      baseFormData: {},
      depsEnum: {
        '1': '平台管理员',
        '2': '运营中心',
        '3': '咨询中心',
        '4': '机构',
        '5': '门店'
      },
      formData: {},
      // 表格字段配置
      columns: [
        {
          title: 'id',
          props: 'id'
        },
        {
          title: '部门类型',
          formatter(row) {
            const { dept_type } = row
            const dEnum = {
              '1': '平台管理员',
              '2': '运营中心',
              '3': '咨询中心',
              '4': '机构',
              '5': '门店',
              '6': '大区'
            }
            return dEnum[dept_type]
          }
        },
        {
          title: '部门名称',
          props: 'dept_name'
        },
        {
          title: '地域',
          props: 'province'
        },
        {
          title: '地址信息',
          props: 'location'
        },
        {
          title: '上级部门ID',
          props: 'dept_parent_id'
        },
        {
          title: '上级部门名称',
          props: 'dept_parent_name'
        },
        {
          title: '电话号码',
          props: 'tel'
        },
        {
          title: '部门邀请码',
          props: 'promotion_code'
        },
        {
          title: '总积分',
          props: 'total_score'
        },
        {
          title: '冻结积分',
          props: 'freeze_score'
        },
        {
          title: '可提现积分',
          props: 'normal_score'
        }
      ],
      id: '',
      baseSearchs: [],
      baseHandles: [
        {
          btnType: 'default',
          text: '新建业务部门',
          key: 'add',
          handle: this.handleBaseSearch
        }
      ],
      configs: {
        loadDataApi: function (p) {
          return new Promise((resolve) => {
            getDeptList(queryParams(p, this.formData)).then((res) => {
              resolve(res)
            })
          })
        },
        fetchListData: function (res) {
          return res.info.data
        },
        fetchTotal: function (res) {
          return 0
        },
        generateQueryParams: function (pagination) {
          const { pageIndex, pageSize } = pagination
          return {
            page: pageIndex,
            limit: pageSize
          }
        }
      },
      operations: [
        {
          label: '编辑',
          handler: (row) => {
            if (row.id === 1) {
              return this.$message.error('平台账号无法编辑')
            }
            this.isShow = true
            this.$nextTick(() => {
              const { id, tel, dept_type, location, dept_parent_id = 0, province, city, promotion_code, dept_parent_name, dept_name } = row
              this.id = id
              let tCity = city
              if (city.indexOf('北京') >= 0 || city.indexOf('上海') >= 0 || city.indexOf('天津') >= 0) {
                tCity = '市辖区'
              }
              const c1 = TextToCode[province] && TextToCode[province].code
              const c2 = TextToCode[province] && TextToCode[province][tCity].code
              this.selectedOptions = [c1, c2]
              this.promotion_code = promotion_code
              this.form = {
                tel,
                dept_type: dept_type.toString(),
                location,
                dept_parent_id: dept_parent_id.toString(),
                dept_parent_name,
                dept_name
              }
            })
          }
        }
      ]
    }
  },
  mounted() {
    const isHidden = !hasPermission('权限管理')
    if (isHidden) {
      this.operations = []
      this.baseHandles = this.baseHandles.filter((item) => item.key !== 'add')
    }
  },
  methods: {
    // 部门类型
    async depChange(val) {
      this.form.dept_parent_id = ''
      const deptType = this.form.dept_type
      // '1': '平台管理员',
      // '2': '运营中心',
      // '3': '咨询中心',
      // '4': '机构',
      // '5': '门店',
      // '6': '大区'
      if (deptType === '3' || deptType === '5' || deptType === '2') {
        const sType = deptType === '3' ? '2' : deptType === '5' ? '4' : '6'
        const result = await getDeptList({ dept_type: sType })
        if (result.code === '0') {
          this.depts = result.info.data
        }
      }
    },
    handleCancleCreate() {
      this.isShow = false
      this.selectedOptions = []
      this.id = ''
      this.form = {
        tel: '',
        dept_type: '',
        location: '',
        dept_parent_id: '',
        promotion_code: '',
        dept_parent_name: ''
      }
    },
    handleBaseSearch() {
      this.isShow = true
    },
    async handleCreatAccount() {
      const formData = this.form
      const depsEnum = this.depsEnum
      const selectedOptions = this.selectedOptions
      const province = CodeToText[selectedOptions[0]]
      let city = CodeToText[selectedOptions[1]]
      if (city === '市辖区' || city === '县') {
        city = province
      }
      formData.dept_parent_name = this.depsEnum[formData.dept_parent_id || 0]
      formData.dept_parent_id = formData.dept_parent_id ? formData.dept_parent_id : '0'
      const id = this.id
      const params = {
        province,
        city,
        dept_name: depsEnum[formData.dept_type],
        ...formData
      }
      if (!params.dept_type) {
        return this.$message.error('请选择部门类型')
      }
      if (!params.dept_name) {
        return this.$message.error('请输入部门名称')
      }
      if (!params.province) {
        return this.$message.error('请选择区域')
      }
      if (!params.location) {
        return this.$message.error('请输入详细地址')
      }
      if (!params.tel) {
        return this.$message.error('请输入详细地址')
      }
      if (!params.tel) {
        return this.$message.error('请输入手机号')
      }
      const phoneReg = /^[1][3,4,5,7,8,9][0-9]{9}$/
      if (!phoneReg.test(params.tel)) {
         return this.$message.error('请输入正确手机号')
      }
      this.loading = true
      if (id) {
        params.id = id
        const result = await updateDept(params)
        this.loading = false
        this.id = ''
        this.promotion_code = ''
        if (result.code === '0') {
          this.$message.success('修改成功')
          this.handleCancleCreate()
          this.$refs.grid.query()
        } else {
          this.$message.error(`修改失败：${result.msg}`)
        }
      } else {
        const result = await createDept(params)
        this.loading = false
        this.promotion_code = ''
        this.id = ''
        if (result.code === '0') {
          this.$message.success('添加成功')
          this.handleCancleCreate()
          this.$refs.grid.query()
        } else {
          this.$message.error(`添加失败：${result.msg}`)
        }
      }
    }
  }
}
</script>
